package com.easylinkin.linkappapi.common.utils;

import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 *
 * @author Tongjie
 * @date 2019-04-10
 **/
public class CommonUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtils.class);

    /**
     * 从实体中解析出字段数据
     *
     * @param data 可能为pojo或者map 从field中解析
     * @param field 字段名称
     */
    @SuppressWarnings("rawtypes")
    public static Object getValue(Object data, String field) {
        if (data instanceof Map) {
            Map map = (Map) data;
            return map.get(field);
        }
        try {
            String method = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
            Method m = data.getClass().getMethod(method);
            if (m != null) {
                return m.invoke(data);
            }
        } catch (Exception e) {
            String error = "data invoke error , data:" + data + " , key:" + field;
            LOGGER.error(error,e);
            return null;
        }
        return null;
    }

    /**
     * 对Map的value按照由大到小的排序
     * @param oldMap
     * @return
     */
    public static Map<String, Double> sortMap(Map<String, Double> oldMap) {
        ArrayList<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(oldMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {

            @Override
            public int compare(Map.Entry<String, Double> arg0,
                               Map.Entry<String, Double> arg1) {
                return (int) (arg1.getValue() - arg0.getValue());
            }
        });
        Map<String, Double> newMap = new LinkedHashMap<String, Double>();
        for (int i = 0; i < list.size(); i++) {
            newMap.put(list.get(i).getKey(), list.get(i).getValue());
        }
        return newMap;
    }

    /**
     * 判断是否为数字
     *
     * @param v
     * @return
     */
    public static boolean isNumber(Object v) {
        if (v == null) {
            return false;
        }
        if (v instanceof Number) {
            return true;
        } else {
            String regex = "^\\d+$";
            if (v.toString().matches(regex)) {
                return true;
            } else {
                String regex1 = "^-?\\d+\\.?\\d+$";
                if (v.toString().matches(regex1)) {
                    return true;
                } else {
                    try {
                        Double.parseDouble(v.toString());
                        return true;
                    } catch (Exception e) {
                        return false;
                    }
                }
            }
        }
    }


    /**
     * 解析为int
     * @param value str
     * @return Integer
     */
    public static Integer parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            throw new BusinessException(value + "不为小于" + Integer.MAX_VALUE + "的整数，请重新输入");
        }
    }

    /**
     * str 解析为long
     * @param value
     * @return
     */
    public static Long parseLong(String value) {
        try {
            return Long.parseLong(value);
        } catch (Exception e) {
            throw new BusinessException(value + "不能转换为整数");
        }
    }

    /**
     * 返回 #{} 或者 ${} 中包含的值
     *
     * @param str
     * @return eg:#{name} ${ages}
     */
    public static String[] getWildcard(String str) {
        List<String> list = new ArrayList<String>();
        int start = 0;
        while (start < str.length() && start >= 0) {
            start = str.indexOf('{', start);
            int end = str.indexOf('}', start);
            if (start > 0) {
                String wc = str.substring(start - 1, end + 1);
                list.add(wc);
            }
            if (start < 0) {
                break;
            }
            start = end + 1;
        }
        return list.toArray(new String[0]);
    }

    /**
     * string 转换为 BIgDecimal
     *
     * @param value 字符串
     * @return BigDecimal
     */
    public static BigDecimal parseBigDecimal(String value) {
        try {
            return new BigDecimal(value);
        } catch (Exception e) {
            throw new BusinessException(value + "不能转换为数字");
        }
    }
}
